package com.mvvm.library.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @创建时间：2023/2/27
 * @作者：小蔡
 * @功能介绍：
 */
public abstract class BaseFragment<T extends ViewBinding,V extends ViewModel> extends Fragment {
    protected T binding;
    protected V viewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = setBinding(inflater, container, savedInstanceState);
        viewModel = (V) new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(getTypeClass());
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
    }

    protected void initData() {

    }

    protected void initView() {

    }

    protected abstract T setBinding(@NonNull LayoutInflater inflater, ViewGroup container, @Nullable Bundle savedInstanceState);

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
    public Class<V> getTypeClass() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        if (type != null) {
            Type[] actualTypeArguments = type.getActualTypeArguments();
            return (Class<V>) actualTypeArguments[1];
        } else {
            return null;
        }
    }
}
